//
//  YYCheckBox.swift
//  S003_CustomControl
//
//  Created by yao_yu on 14-9-11.
//  Copyright (c) 2014年 yao_yu. All rights reserved.
//

import UIKit

private let CHECK_ICON_WH:CGFloat     = 15
private let ICON_TITLE_MARGIN:CGFloat = 5.0
private let TITLE_LEFT = CHECK_ICON_WH + ICON_TITLE_MARGIN


protocol YYCheckBoxDelegate{
    func didSelect(checkbox:YYCheckBox!, selected:Bool)
}

class YYCheckBox: UIButton {
    
    var checked = false
    var delegate:YYCheckBoxDelegate?
    
    override init() {
        super.init()
    }
    
    func reSet() {
        self.setImage(UIImage(named: "checkbox_checked@2x.png"), forState: UIControlState.Selected)
        self.setImage(UIImage(named: "checkbox_unchecked@2x.png"), forState: UIControlState.Normal)
        self.addTarget(self, action: "onClick", forControlEvents: UIControlEvents.TouchUpInside)
        self.setChecked(true)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func setDelegate(delegate:YYCheckBoxDelegate?){
        self.delegate = delegate
    }
    
    override func imageRectForContentRect(contentRect: CGRect) -> CGRect {
        return CGRectMake(
            0,
            (self.frame.height - CHECK_ICON_WH)/2.0,
            CHECK_ICON_WH,
            CHECK_ICON_WH)
    }
    
    override func titleRectForContentRect(contentRect: CGRect) -> CGRect {
        return CGRectMake(
            TITLE_LEFT,
            0,
            self.frame.width - TITLE_LEFT - ICON_TITLE_MARGIN,
            self.frame.height)
    }

    func setChecked(checked:Bool){
        if checked == self.checked{
            return
        }
        self.checked = checked
        self.selected = checked
        if delegate != nil{
            delegate?.didSelect(self, selected: checked)
        }
    }
    
    func onClick(){
        self.setChecked(!self.checked)
    }
    
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect)
    {
        // Drawing code
    }
    */

}
